package com.imooc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.enums.CommentLevel;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.*;
import com.imooc.pojo.*;
import com.imooc.pojo.vo.ItemCommentLebelCountsVO;
import com.imooc.pojo.vo.ItemCommentVO;
import com.imooc.pojo.vo.SearchItemVO;
import com.imooc.pojo.vo.ShopcartVO;
import com.imooc.service.ItemService;
import com.imooc.utils.DesensitizationUtil;
import com.imooc.utils.PagedGridResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
@Transactional
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemsMapper itemsMapper;

    @Autowired
    private ItemsImgMapper itemsImgMapper;

    @Autowired
    private ItemsSpecMapper itemsSpecMapper;

    @Autowired
    private ItemsParamMapper itemsParamMapper;

    @Autowired
    private ItemsCommentsMapper itemsCommentsMapper;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Items queryItemById(String itemId) {

//        Example example=new Example(Items.class);
//        Example.Criteria criteria=example.createCriteria();
//
//        criteria.andEqualTo("id",itemId);
//
//        Items items=itemsMapper.selectByPrimaryKey(example);

        return itemsMapper.selectByPrimaryKey(itemId);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<ItemsImg> queryItemImgList(String itemId) {

        Example example=new Example(ItemsImg.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("itemId",itemId);

        List<ItemsImg> itemsImgList=itemsImgMapper.selectByExample(example);

        return itemsImgList;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<ItemsSpec> queryItemsSpecList(String itemId) {

        Example example=new Example(ItemsSpec.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("itemId",itemId);
        List<ItemsSpec> itemsSpecList=itemsSpecMapper.selectByExample(example);

        return itemsSpecList;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ItemsParam queryItemsParam(String itemId) {

        Example example=new Example(ItemsParam.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("itemId",itemId);

        ItemsParam itemsParam=itemsParamMapper.selectOneByExample(example);

        return itemsParam;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ItemCommentLebelCountsVO queryCommentCounts(String itemId) {

        Integer goodCounts=getCommentCouns(itemId,CommentLevel.GOOD.type);
        Integer normalCounts=getCommentCouns(itemId,CommentLevel.NORMAL.type);
        Integer badCounts=getCommentCouns(itemId,CommentLevel.BAD.type);

        ItemCommentLebelCountsVO countsVO=new ItemCommentLebelCountsVO();
        countsVO.setGoodCounts(goodCounts);
        countsVO.setNormalCounts(normalCounts);
        countsVO.setBadCounts(badCounts);
        countsVO.setTotalCounts(goodCounts+normalCounts+badCounts);

        return countsVO;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public Integer getCommentCouns(String itemId,Integer level){
        ItemsComments itemsComments=new ItemsComments();
        itemsComments.setItemId(itemId);
        if (level != null){
            itemsComments.setCommentLevel(level);
        }
        return itemsCommentsMapper.selectCount(itemsComments);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public PagedGridResult queryItemComments(String itemId, Integer level,Integer page,Integer pageSize) {
        Map<String,Object> paramsMap=new HashMap<>();
        paramsMap.put("itemId",itemId);
        paramsMap.put("level",level);

        /**
         * page: 第几页
         * pageSize: 每页显示条数
         */
        PageHelper.startPage(page, pageSize);

        List<ItemCommentVO> list=itemsCommentsMapper.queryItemComments(paramsMap);

        for (ItemCommentVO vo: list){
            vo.setNickname(DesensitizationUtil.commonDisplay(vo.getNickname()));

        }

        return setterPagedGrid(list,page);
    }

    private PagedGridResult setterPagedGrid(List<?> list,Integer page){
        PageInfo<?> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());

        return grid;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize) {
        Map<String,Object> paramsMap=new HashMap<>();
        paramsMap.put("keywords",keywords);
        paramsMap.put("sort",sort);


        PageHelper.startPage(page, pageSize);

        List<SearchItemVO> list=itemsCommentsMapper.searchItems(paramsMap);


        return setterPagedGrid(list,page);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public PagedGridResult searchItemsByThirdCat(Integer catId, String sort, Integer page, Integer pageSize) {
        Map<String,Object> paramsMap=new HashMap<>();
        paramsMap.put("catId",catId);
        paramsMap.put("sort",sort);


        PageHelper.startPage(page, pageSize);

        List<SearchItemVO> list=itemsCommentsMapper.searchItemsByThirdCat(paramsMap);


        return setterPagedGrid(list,page);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<ShopcartVO> queryItemsBySpecIds(String specIds) {

        String ids[] =specIds.split(",");
        List<String> specIdsList=new ArrayList<>();
        Collections.addAll(specIdsList,ids);

        return itemsCommentsMapper.queryItemsBySpecIds(specIdsList);


    }


    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ItemsSpec queryItemSpecById(String specId) {
        return itemsSpecMapper.selectByPrimaryKey(specId);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public String queryItemMainImgById(String itemId) {

        ItemsImg itemsImg=new ItemsImg();

        itemsImg.setItemId(itemId);
        itemsImg.setIsMain(YesOrNo.YES.type);

        ItemsImg result = itemsImgMapper.selectOne(itemsImg);

        return result!=null ? result.getUrl() : "";
    }

    @Override
    public void decreaseItemSpecStock(String specId, Integer buyCounts) {

        //synchronized 不推荐使用，集群下无用，性能低下
        //锁数据库：不推荐，导致数据库性能低下
        //分布式锁 zookeeper redis

        //1.查询库存
//        int stock=2;
//        //2.判断库存，是否能够减少到0以下
//        if(stock-buyCounts<0){
//
//        }
        int result=itemsCommentsMapper.decreaseItemSpecStock(specId,buyCounts);
        if (result!=1){
            throw  new RuntimeException("订单创建失败，原因：库存不足");
        }

    }
}
